package com.dataimport.service.impl;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dataimport.entity.sourceentity.EnjoyRunningDataInfo;
import com.dataimport.entity.sourceentity.StudentQualityEducationInfo;
import com.dataimport.entity.targetentity.FunnyRunInfo;
import com.dataimport.entity.targetentity.QualityIntegrate;
import com.dataimport.entity.targetentity.SchoolCalendar;
import com.dataimport.mapper.FunnyRunInfoMapper;
import com.dataimport.mapper.EnjoyRunningDataInfoMapper;
import com.dataimport.mapper.InsertSchoolCalendarMapper;
import com.dataimport.service.FunnyRunInfoService;
import com.dataimport.utils.HasNullFieldUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author 卑微小峰
 * @date 2022/9/27
 */
@Service
public class FunnyRunInfoServiceImpl extends ServiceImpl<FunnyRunInfoMapper, FunnyRunInfo> implements FunnyRunInfoService {

    private static long PAGE_SIZE = 1000;

    private Cache<String, Long> fifoCache;

    @Autowired
    private InsertSchoolCalendarMapper insertSchoolCalendarMapper;

    @Autowired
    private EnjoyRunningDataInfoMapper enjoyRunningDataInfoMapper;

    @Override
    public void dealWithFunnyRunInfo() {
        List<SchoolCalendar> schoolCalendarList = insertSchoolCalendarMapper.selectList(null);
        fifoCache = CacheUtil.newFIFOCache(schoolCalendarList.size());
        for (SchoolCalendar schoolCalendar : schoolCalendarList) {
            String key = schoolCalendar.getSchoolYear().trim().replace(" ", "") + "-" + schoolCalendar.getSemester();
            fifoCache.put(key, schoolCalendar.getId());
        }

        long currentPage = 0L;
        while (true) {
            currentPage++;
            List<FunnyRunInfo> funnyRunInfoList = selectData(currentPage);
            if (ObjectUtils.isEmpty(funnyRunInfoList)) {
                break;
            }
            insertData(funnyRunInfoList);
            System.out.println("乐跑信息导入成功");
        }
    }

    public List<FunnyRunInfo> selectData(long currentPage) {
        DynamicDataSourceContextHolder.push("mysql2");
        IPage<EnjoyRunningDataInfo> page = new Page<>();
        page.setCurrent(currentPage);
        page.setSize(PAGE_SIZE);
        IPage<EnjoyRunningDataInfo> data = enjoyRunningDataInfoMapper.selectPage(page, null);
        DynamicDataSourceContextHolder.poll();

        List<EnjoyRunningDataInfo> enjoyRunningDataInfoList = data.getRecords();
        List<FunnyRunInfo> funnyRunInfoList = enjoyRunningDataInfoList.stream()
                .filter(enjoyRunningDataInfo -> HasNullFieldUtil.inExistenceNull(enjoyRunningDataInfo) &&
                        enjoyRunningDataInfo.getMovementDistance() != null &&
                        enjoyRunningDataInfo.getMovementDistance() >= 0 &&
                        enjoyRunningDataInfo.getXnxq().length() == 11)
                .map(enjoyRunningDataInfo -> {
                    FunnyRunInfo funnyRunInfo = new FunnyRunInfo();
                    String[] str = enjoyRunningDataInfo.getXnxq().split("-");
                    BeanUtils.copyProperties(enjoyRunningDataInfo, funnyRunInfo);
                    if ("1".equals(str[2])) {
                        String key = str[0] + "-" + str[1] + "-0";
                        funnyRunInfo.setCalendarId(fifoCache.get(key));
                    }else if ("2".equals(str[2])) {
                        String key = str[0] + "-" + str[1] + "-1";
                        funnyRunInfo.setCalendarId(fifoCache.get(key));
                    }else {
                        return null;
                    }
                    return funnyRunInfo;
                })
                .collect(Collectors.toList());

        return funnyRunInfoList;
    }

    @Transactional(rollbackFor = Exception.class)
    public void insertData(List<FunnyRunInfo> funnyRunInfoList) {
        try {
            DynamicDataSourceContextHolder.push("mysql1");
            this.saveBatch(funnyRunInfoList, funnyRunInfoList.size());
            DynamicDataSourceContextHolder.poll();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }


}
